package com.g4m.baselib.fegin;

import com.alibaba.fastjson.JSONObject;
import com.g4m.baselib.entity.SnsNdkPublic;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 对外接口拦截器
 * Created on 2020-01-01
 * <p>Copyright 2008-2020 snsndk.com</p>
 */
@Component
@Slf4j
public class FeginRequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpRequest, HttpServletResponse response, Object handler) {
        //初始化填充公共数据到Request中
        this.initLocalByRequest(httpRequest);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        FeginPublicDataHolder.clear(request);
        MDC.clear();
    }

    private void initLocalByRequest(HttpServletRequest servletRequest) {

        //解析公共加密参数到对象中由会话线程中保存
        String p = servletRequest.getHeader("p");
        if (StringUtils.isNotBlank(p)) {
            try {
                SnsNdkPublic snsNdkPublic = JSONObject.parseObject(p, SnsNdkPublic.class);
                if (snsNdkPublic != null) {
                    FeginPublicDataHolder.setSnsNdkPublic(servletRequest, snsNdkPublic);
                }
            } catch (Exception ignore) {
            }
        }

        FeginPublicDataHolder.setHttpServletRequest(servletRequest);
    }
}
